<template>
  <view class="login-container">
    <!-- 提示登录的图标 -->
    <uni-icons type="contact-filled" size="100" color="#AFAFAF"></uni-icons>
    <!-- 登录按钮 -->
    <button type="primary" class="btn-login bg-green" @click="getUserInfo">一键登录</button>
    <!-- 登录提示 -->
    <view class="tips-text">登录后尽享更多权益</view>
  </view>
</template>

<script>
  import {
    mapMutations,
    mapState
  } from 'vuex'
  export default {
    name: "user-login",
    data() {
      return {

      };
    },
    computed: {
      ...mapState('m_user', ['redirectInfo'])
    },
    methods: {
      ...mapMutations('m_user', ['updateUserInfo', 'updateToken', 'updateRedirectInfo']),
      //获取用户基本信息
      getUserInfo() {
        // 判断是否获取用户信息成功
        uni.getUserProfile({
          desc: '登录', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
          success: async (res) => {
            const db = uniCloud.database();
            const {
              result: getUserInfo
            } = await db.collection("my_user").get();
            const result = getUserInfo.data.find(item => {
              return item.user_name == res.userInfo.nickName;
            })
            console.log(result);
            // 判断用户名是否存在 新用户 新增
            if (result === undefined) {
              const myUser = {
                user_name: res.userInfo.nickName,
                avatarUrl: res.userInfo.avatarUrl
              }
              await db.collection("my_user").add(myUser)
              //用户不存在 获取新增的数据持久化存储本地
              const {
                result: newUserInfo
              } = await db.collection("my_user").where({
                user_name: myUser.user_name
              }).get();
              console.log(newUserInfo.data[0]);
              this.updateUserInfo(newUserInfo.data[0]);
            } else {
              //用户存在 将获取数据持久化存储本地
              this.updateUserInfo(result);
            }
            this.getToken(res)
          },
          fail: (res) => {
            return uni.$showMsg('您取消了登录授权！')
          }
        });
      },
      async getToken(info) {
        //获取code对应的值
        const res = await uni.login().catch(err => err);
        // console.log(res);
        if (res.errMsg !== 'login:ok') return uni.$showMsg('登录失败！')

        //自定义一个随机token
        const newtoken = this.generateToken();
        this.updateToken(newtoken)
        this.navigateBack()
      },
      navigateBack() {
        if (this.redirectInfo && this.redirectInfo.openType === 'switchTab') {
          uni.switchTab({
            url: this.redirectInfo.from,
            complete: () => {
              this.updateRedirectInfo(null)
            }
          })
        }
      },
      //生成随机token
      generateToken() {
        let token = '';
        const tokenLength = 32;
        const possibleChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

        for (let i = 0; i < tokenLength; i++) {
          token += possibleChars.charAt(Math.floor(Math.random() * possibleChars.length));
        }

        return token;
      },

    },
  }
</script>

<style lang="scss">
  .login-container {
    // 登录盒子的样式
    height: 700px;
    flex: auto;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    position: relative;
    overflow: hidden;


    // 登录按钮的样式
    .btn-login {
      width: 90%;
      border-radius: 100px;
      margin: 15px 0;
    }

    // 按钮下方提示消息的样式
    .tips-text {
      font-size: 12px;
      color: gray;
    }
  }
</style>